package com.cuiweiyou.mysqljdbc.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import com.cuiweiyou.mysqljdbc.model.MysqlConfig;

import android.util.Log;

/**
 * Mysql工具类
 * 
 * @author TS-YFZX-CWY
 */
public class MysqlUtil {
	public static Connection conn;

	private MysqlUtil() {
	}

	/**
	 * 获取数据库连接
	 * 
	 * @throws ClassNotFoundException
	 * @throws SQLException
	 */
	public static void getConnection() throws ClassNotFoundException, SQLException {
		if (null == conn){
			Class.forName("com.mysql.jdbc.Driver");
			conn = DriverManager.getConnection(MysqlConfig.DB_REMOTEADDRESS, MysqlConfig.USER_NAME, MysqlConfig.USER_PSWD);
		}
	}

	/**
	 * 获取查询结果集
	 * 
	 * @param sql 查询语句
	 */
	public static void getResultSet(String sql) {
		try {
			Statement stmt = conn.createStatement();
			ResultSet rs = stmt.executeQuery(sql);
			while (rs.next()) {
				Log.e("ard", "name:" + rs.getString("username") + ", addr:" + rs.getString("useraddr"));
			}
			rs.close();
			stmt.close();
			stmt = null;
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 关闭数据库连接
	 * 
	 * @throws SQLException
	 */
	public static void destoryConnection() throws SQLException {
		if (null != conn)
			conn.close();

		conn = null;
	}
}
